package com.bbcare.followup.plat.task;

import com.bbcare.comm.*;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.entity.FuClosecaseRecord;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PatientTask;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.FuClosecaseRecordDao;
import com.bbcare.followup.plat.store.ibatis.IFollowQueueDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.util.CollectionUtils;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Title CloseCaskJobTask.java
 * @Package com.bbcare.followup.plat.task
 * @Description 结案定时任务
 * @Author        <a href="mailto:jiangqian_java@163.com">jiang</a>
 * @Date 2022/7/5
 * @Version V1.0
 * @Copyright (c) Shanghai BBcare Medical Equipment Co.,Ltd.
 */
public class CloseCaskJobTask implements Job {

    private final Log logger = LogFactory.getLog(CloseCaskJobTask.class);

    @Autowired
    private IPatientService patientSerivce;

    @Autowired
    private IFollowQueueDAO queueDao;

    @Autowired
    private IPatientDAO patientDao;

    @Autowired
    private FuClosecaseRecordDao fuClosecaseRecordDao;

    @Override
    public void execute(JobExecutionContext context) {
        //logger.warn("---start: CloseCaskJobTask---" + DateUtil.getMillSysDate());

        List<PatientTask> epList = null;

        Map<String, Object> paramIn = new HashMap<String, Object>();
        paramIn.put("start", 0);
        paramIn.put("end", 100);// 每次提取100条
        paramIn.put("taskStatus", Constants.PATIENT_TASK_STATUS_EXPIRED);   //过期的随访任务。
        paramIn.put("expiredTime", DateUtil.getCurrDateByDay(1, Constants.SUBTRACT_CHAR));// 截止时间=昨天
        paramIn.put("opCode", Constants.OP_CODE_3001);
        paramIn.put("opType", Constants.OP_TYPE_BG_ADMIN);
        paramIn.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
        List<String> taskTypeInList = new ArrayList<String>();
        taskTypeInList.add(Constants.TASK_TYPE_SCHEME_SCHEDULE);// 门诊任务
        taskTypeInList.add(Constants.TASK_TYPE_SCHEME_TEMP);// 线上随访
        paramIn.put("taskTypeIn", taskTypeInList);
        String authorId = Constants.BG_LOGIN_NO_ADMIN;// 后台程序处理工号
        int totalNum = 0;

        try {
            epList = patientSerivce.selectCloseTask(paramIn);
        } catch (Exception ex) {
            //logger.error(ex.getMessage());
            return;
        }

        if (!CollectionUtils.isEmpty(epList)) {
            Map<String, Object> dealIn = new HashMap<String, Object>();
            PatientTask ptVo = new PatientTask();
            int iep = epList.size();
            int k = 0;
            for (k = 0; k < iep; k++) {
                dealIn.clear();
                ptVo = epList.get(k);
                dealIn.put("taskId", ptVo.getId());
                dealIn.put("userId", ptVo.getUserId());
                dealIn.put("taskName", ptVo.getTaskName());
                dealIn.put("ptSchemeId", ptVo.getPtSchemeid());
                dealIn.put("queueId", ptVo.getQueueId());
                dealIn.put("authorId", authorId);
                dealIn.put("taskType", ptVo.getTaskType());
                dealIn.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));
                dealIn.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));
                dealIn.put("opCode", Constants.OP_CODE_3001);
                dealIn.put("opType", Constants.OP_TYPE_BG_ADMIN);

                // 队列信息校验
                HashMap<String, Object> queueInMap = new HashMap<String, Object>();
                queueInMap.put("id", ptVo.getQueueId());
                List<FollowQueue> queueList = null;
                try {
                    queueList = queueDao.selectById(queueInMap);
                } catch (Exception ex) {
                    //logger.error(ex.getMessage());
                }
                if (queueList.isEmpty()) {
                    //随访任务无对应的队列存在，继续下一个任务。
                    continue;
                }

                String tenantId = queueList.get(0).getTenantId();
                if (null == queueList || 0 == queueList.size()) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_QUEUE_NOT_EXIST, "未查询到对应队列信息！"));
                }

                Map<String, Object> ptInMap = new HashMap<String, Object>();
                ptInMap.put("userId", ptVo.getUserId());
                ptInMap.put("tenantId", tenantId);
                Patient ptOut = null;
                try {
                    ptOut = patientDao.selectById(ptInMap);
                } catch (Exception ex) {
                    //logger.error(ex.getMessage());
                }
                if (null == ptOut) {
                    throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "查询无此患者记录！"));
                }

                try {
                    /**
                     * 任务失访并且为随访期最后一个节点
                     * 也就是该患者随访任务结束，结案了
                     * 入fu_closecase_record结案记录表
                     */
                    if (PropertiesUtils.getProperty("isCloseTask").equals("true")) {
                        if (StringUtils.isEmpty(ptVo.getNextTaskId()) && DateUtil.daysBetweenDateStr(ptVo.getEndTime(), DateUtil.getCurrDate2()) >= 0) {
                            //查询该病人是否已经结案
                            HashMap<String, Object> map = new HashMap<String, Object>();
                            map.put("authorId", authorId);
                            map.put("tenantId", tenantId);
                            map.put("userId", ptVo.getUserId());
                            HashMap<String, Object> retMap = patientSerivce.pageList(map);
                            if (null != retMap) {
                                List rows = (List) retMap.get("rows");
                                if (rows.size() > 0) {
                                    //logger.error("患者" + ptOut.getUserName() + "已结案");
                                    continue;
                                }
                            }
                            FuClosecaseRecord temp = new FuClosecaseRecord();
                            temp.setId(SeqUtil.getSeqNo());
                            temp.setUserId(ptOut.getId());
                            temp.setUserName(ptOut.getUserName());
                            temp.setPhone(ptOut.getPhoneNo());
                            temp.setGender(ptOut.getGender());
                            temp.setBirthdate(DateUtil.getDate(ptOut.getBirthday()));
                            temp.setCloseType(Constants.FOLLOWUP_OVER);//手动中止
                            temp.setTenantId(ptOut.getTenantId());
                            temp.setCloseReason("随访期结束");
                            temp.setCreateTime(new Date());
                            temp.setQueueId(ptVo.getQueueId());
                            temp.setTaskId(ptVo.getId());
                            temp.setCreater(authorId);
                            temp.setTenantId(tenantId);
                            temp.setPtSchemeid(ptVo.getPtSchemeid());
                            fuClosecaseRecordDao.insert(temp);
                        }
                    }

                    totalNum++;
                } catch (AppException e) {
                    //logger.error("CloseCaskJobTask AppException...dealIn==" + dealIn.toString());

                    // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                    try {
                        dealIn.put("errMsg", e.getErrMsg());
                        patientSerivce.savePtExcpInfo(dealIn);
                    } catch (Exception e1) {
                        //logger.error("---CloseCaskJobTask AppException---dealIn==" + dealIn.toString());
                    }
                } catch (Exception ex) {
                    //logger.error("CloseCaskJobTask Exception...dealIn==" + dealIn.toString());

                    // 将错误记录存在异常表pt_excp_rd中，后续查询过滤掉这批数据
                    try {
                        dealIn.put("errMsg", "CloseCaskJobTask Exception:" + ex.getMessage());
                        patientSerivce.savePtExcpInfo(dealIn);
                    } catch (Exception ex2) {
                        //logger.error("---savePtExcpInfo Exception---dealIn==" + dealIn.toString());
                    }
                }
            }
        } else {
            //logger.warn("---CloseCaskJobTask.execute() epList is EMPTY!");
        }

        //logger.warn("---end: CloseCaskJobTask---total deal==" + totalNum);

        return;
    }
}
